import 'package:pacsun/components/appbar.dart';
import 'package:pacsun/model/taskModel.dart';
import 'package:pacsun/provider/taskListProv.dart';
import 'package:pacsun/provider/userProv.dart';
import 'package:pacsun/view/task/theme/app_colors.dart';
import 'package:pacsun/view/task/widgets/animated_nnderline_tabBar.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import './widgets/task_card.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

class TaskPage extends StatefulWidget {
  const TaskPage({super.key});

  @override
  State<TaskPage> createState() => _TaskPageState();
}

class _TaskPageState extends State<TaskPage> with RouteAware {
  late final TaskListProv _taskListProv;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _taskListProv = Provider.of<TaskListProv>(context, listen: false);
      _taskListProv.setAid(context.read<UserProvider>().currentUser!.aid!);
      _initData();
    });
  }

  @override
  void dispose() {
    _taskListProv.claerAll();
    super.dispose();
  }

  Future<void> _initData() async {
    try {
      _taskListProv.getCategoryList();
    } catch (e) {
      debugPrint('初始化数据失败: $e');
    }
  }

  void _handleFilterTagTap(String tag) {
    _taskListProv.filterTagTask(tag);
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<TaskListProv>(
      builder: (context, taskListProv, child) {
        return MediaQuery(
          data:
              MediaQuery.of(context).copyWith(textScaler: TextScaler.noScaling),
          child: Scaffold(
            backgroundColor: Colors.black,
            extendBodyBehindAppBar: true,
            appBar: const CommonTransparentAppBar(),
            body: Stack(children: [
              const AppBarBg(),
              SafeArea(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _buildTabBar(taskListProv),
                    Expanded(
                      child: PageView(
                        controller: taskListProv.pageController,
                        onPageChanged: taskListProv.pageChanged,
                        children: taskListProv.categoryData.values.map(
                          (e) {
                            return Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                _buildFilterTags(e.types, e.tagValue),
                                SizedBox(height: 16.h),
                                Expanded(
                                  child: TaskCategoryPageView(
                                    taskType: e.taskType,
                                    tasks: e.filterList,
                                    onRefresh: () =>
                                        taskListProv.refreshCurrentCategory(),
                                    onLoadMore: () =>
                                        taskListProv.loadMoreCurrentCategory(),
                                    hasMore: e.hasMore,
                                    refreshController: e.refreshController,
                                  ),
                                )
                              ],
                            );
                          },
                        ).toList(),
                      ),
                    ),
                  ],
                ),
              ),
            ]),
          ),
        );
      },
    );
  }

  Widget _buildTabBar(TaskListProv taskListProv) {
    final currentIndex = taskListProv.tabCurrent;
    return AnimatedUnderlineTabBar(
      tabs: TaskListProv.categoryConfig.values.toList(),
      selectedIndex: currentIndex,
      padding: EdgeInsets.only(top: 0, left: 16, right: 16, bottom: 16).r,
      onTabTap: taskListProv.setTabCurrent,
      unselectedTextStyle:
          customTextStyle(fontSize: 24, opacity: 0.5, fontWeight: 500),
      selectedTextStyle: customTextStyle(fontSize: 24, fontWeight: 700),
      lineWidth: 35.w,
      lineHeight: 6.h,
    );
  }

  Widget _buildFilterTags(Map<String, String> tags, String tagValue) {
    return SizedBox(
      height: 32.h,
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        padding: const EdgeInsets.symmetric(horizontal: 16).r,
        child: Row(
          children: tags.entries
              .map((tag) => _buildFilterTag(tag.key, tagValue))
              .toList(),
        ),
      ),
    );
  }

  Widget _buildFilterTag(String tag, String selectTag) {
    return GestureDetector(
      onTap: () => _handleFilterTagTap(tag),
      child: Container(
        margin: const EdgeInsets.only(right: 8).r,
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6).r,
        decoration: BoxDecoration(
          color: selectTag == tag
              ? Colors.white
              : const Color(0xFFD9D9D9).withAlpha(10),
          borderRadius: BorderRadius.circular(10),
        ),
        child: Text(
          tag,
          style: TextStyle(
            color: selectTag == tag ? Colors.black : Colors.white,
            fontSize: 12.sp,
            height: 1,
          ),
        ),
      ),
    );
  }
}

class TaskCategoryPageView extends StatelessWidget {
  final String taskType;
  final List<TaskModal> tasks;
  final Future<void> Function() onRefresh;
  final Future<void> Function() onLoadMore;
  final bool hasMore;
  final RefreshController refreshController;

  const TaskCategoryPageView({
    super.key,
    required this.taskType,
    required this.tasks,
    required this.onRefresh,
    required this.onLoadMore,
    required this.hasMore,
    required this.refreshController,
  });

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      enablePullDown: true,
      enablePullUp: hasMore,
      header: const WaterDropHeader(
        waterDropColor: Colors.white,
      ),
      controller: refreshController,
      onRefresh: onRefresh,
      onLoading: onLoadMore,
      footer: const ClassicFooter(
        noDataText: '',
        loadStyle: LoadStyle.ShowWhenLoading,
      ),
      child: ListView.builder(
        padding: const EdgeInsets.symmetric(horizontal: 16),
        itemCount: tasks.length,
        itemBuilder: (context, index) {
          return TaskCard(
            task: tasks[index],
            type: taskType,
            fromType: 1,
            index: index,
          );
        },
      ),
    );
  }
}
